const CryptoJS = require("crypto-js");
const { WEB_PREFIX, WEB_UPLOAD_IMAGE_PATH, WEB_UPLOAD_DEMO_PATH, LOGIN_CRYPTO_KEY } = process.env;
const DEFAULT_SIZE = 20;

module.exports = {
  webSitePrefix: WEB_PREFIX,
  uploadImagePath: WEB_UPLOAD_IMAGE_PATH,
  uploadDemoPath: WEB_UPLOAD_DEMO_PATH,
  resourcePrefix: `${WEB_PREFIX}${WEB_UPLOAD_IMAGE_PATH}`,
  demoFilePrefix: `${WEB_PREFIX}${WEB_UPLOAD_DEMO_PATH}`,
  webPageSize: DEFAULT_SIZE,
  getQueryStr(obj) {
    return Object.entries(obj)
      .map(([k, v]) => `${k}=${v}`)
      .join('&');
  },
  setDefaultPageAndSize(page, size) {
    page = parseInt(page) || 1;
    size = parseInt(size) || DEFAULT_SIZE;
    if (page < 2) {
      page = 1;
    }
    if (size <= 0) {
      size = DEFAULT_SIZE;
    }
    return { page, size };
  },
  getFileType(name) {
    return String(String(name).split('.').pop()).toLowerCase();
  },
  parseTime(time, cFormat) {
    if (arguments.length === 0 || !time) {
      return null;
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
    let date;
    if (typeof time === 'object') {
      date = time;
    } else {
      if (typeof time === 'string') {
        if (/^[0-9]+$/.test(time)) {
          time = parseInt(time);
        } else {
          time = time.replace(new RegExp(/-/gm), '/');
        }
      }
      if (typeof time === 'number' && time.toString().length === 10) {
        time = time * 1000;
      }
      date = new Date(time);
    }
    const formatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay(),
    };
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
      const value = formatObj[key];
      if (key === 'a') {
        return ['日', '一', '二', '三', '四', '五', '六'][value];
      }
      return value.toString().padStart(2, '0');
    });
    return time_str;
  },

  parseCrypto(encryptedPassword) {
    const bytes = CryptoJS.AES.decrypt(encryptedPassword, LOGIN_CRYPTO_KEY, {
      mode: CryptoJS.mode.ECB, // 模式需与前端的加密配置一致
      padding: CryptoJS.pad.Pkcs7 // 填充模式也需一致
    });
    return bytes.toString(CryptoJS.enc.Utf8);
  }
};
